package org.onion.pattern.event.spring.outbox;

import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.onion.pattern.event.outbox.data.OutboxEventStatus;
import org.onion.pattern.event.outbox.data.OutboxEventInfo;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Map;

public class OutboxEventInfoRowMapper implements RowMapper<OutboxEventInfo> {
    public static final String                   TABLE_NAME = "_outbox_event";
    public final static String                   COLUMNS    =
            " id, event_key, event_group, event_status, event_time, domain_id, domain_type, channel, topic, sub_topic, " +
                    "serializer, publish_time, created_time, props, payload, ver  ";
    public final static OutboxEventInfoRowMapper INSTANCE   = new OutboxEventInfoRowMapper();

    @Override
    public OutboxEventInfo mapRow(ResultSet resultSet, int i) throws SQLException {
        OutboxEventInfo storedEvent = new OutboxEventInfo();
        storedEvent.setId(resultSet.getLong(1));
        storedEvent.setEventKey(resultSet.getString(2));
        storedEvent.setGroup(resultSet.getString(3));
        storedEvent.setOutBoxEventStatus(OutboxEventStatus.fromCode(resultSet.getInt(4)));
        storedEvent.setEventTime( resultSet.getLong(5));
        storedEvent.setDomainId(resultSet.getString(6));
        storedEvent.setDomainType(resultSet.getString(7));
        storedEvent.setChannel(resultSet.getString(8));
        storedEvent.setTopic(resultSet.getString(9));
        storedEvent.setSubTopic(resultSet.getString(10));
        storedEvent.setSerializer(resultSet.getString(11));
        storedEvent.setPublishTime((LocalDateTime) resultSet.getObject(12));
        storedEvent.setCreateTime((LocalDateTime) resultSet.getObject(13));
        String props = resultSet.getString(14);
        storedEvent.setProps(Collections.emptyMap());
        if (StringUtils.isNotBlank(props)) {
            storedEvent.setProps(JSONUtil.toBean(props, Map.class));
        }
        storedEvent.setPayload(resultSet.getBytes(15));
        storedEvent.setVer(resultSet.getLong(16));

        return storedEvent;
    }
}

